package com.Unidbg_hengdin.filehandle;

import com.alibaba.fastjson.util.IOUtils;
import com.github.unidbg.AndroidEmulator;
import com.github.unidbg.Emulator;
import com.github.unidbg.Module;
import com.github.unidbg.arm.backend.Unicorn2Factory;
import com.github.unidbg.file.FileResult;
import com.github.unidbg.file.IOResolver;
import com.github.unidbg.linux.android.AndroidEmulatorBuilder;
import com.github.unidbg.linux.android.AndroidResolver;
import com.github.unidbg.linux.android.dvm.*;
import com.github.unidbg.linux.file.ByteArrayFileIO;
import com.github.unidbg.linux.file.SimpleFileIO;
import com.github.unidbg.memory.Memory;

import java.io.File;

public class Study0901 extends AbstractJni implements IOResolver {
    private final AndroidEmulator emulator;
    private final VM vm;

    private final Module module;

    private final DvmClass NativeHelperUtils;

    private final boolean logging;

    Study0901(boolean logging){
        this.logging = logging;
        emulator = AndroidEmulatorBuilder.for64Bit()
                .setProcessName("com.xiaojianbang.app")
                .addBackendFactory(new Unicorn2Factory(true))
                .build();

        final Memory memory = emulator.getMemory();
        memory.setLibraryResolver(new AndroidResolver(23));

        // IOResolver
        emulator.getSyscallHandler().addIOResolver(this);

        vm = emulator.createDalvikVM();
        vm.setVerbose(logging);
        vm.setJni(this);

        DalvikModule dalvikModule = vm.loadLibrary(new File("unidbg-android/src/test/java/com/Unidbg_hengdin/filehandle/libxiaojianbang.so"), false);

        module = dalvikModule.getModule();
        NativeHelperUtils = vm.resolveClass("com/xiaojianbang/ndk/NativeHelper");
    }

    public static void main(String[] args){
        Study0901 study09 = new Study0901(true);
        study09.callFun();
        study09.destory();
    }

    void destory(){
        IOUtils.close(emulator);
        if(logging){
            System.out.println("destory ...");
        }
    }
    void callFun(){
        StringObject res = NativeHelperUtils.callStaticJniMethodObject(emulator,"readSomething()");
        System.out.println("readSomething : "+ res.getValue());
    }
    @Override
    public FileResult resolve(Emulator emulator, String pathname, int oflags) {
        System.out.println("pathname -------------: " + pathname);
        if("/proc/self/maps".equals(pathname)){
            return FileResult.success(new SimpleFileIO(oflags,new File("F:\\unidbg-master\\unidbg-android\\src\\test\\java\\com\\Unidbg_hengdin\\filehandle\\maps"),pathname));
//            return FileResult.success(new ByteArrayFileIO(oflags, pathname,"hengdin test unidbg filehandler !".getBytes()));
        }
        return null;
    }

}
